package cn.jn.lhm.uc.handler;

import cn.jn.lhm.service.config.exception.GlobalException;
import cn.jn.lhm.uc.constant.WxConstant;
import cn.jn.lhm.uc.entity.UcenterMember;
import cn.jn.lhm.uc.service.UcService;
import cn.jn.lhm.uc.utils.HttpClientUtils;
import cn.jn.lhm.utils.JwtUtils;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

/**
 * @author LHM
 * @Tips 热爱每一天，奋斗每一天
 * @date 2020/6/12 - 19:28
 */
@Controller
@RequestMapping("/api/ucenter/wx")
@Slf4j
public class WxHandler {

    @Resource
    private UcService ucService;

    @GetMapping("/login")
    public String getWXCode() {
        //固定的地址，进行参数的拼接
        //相当于问好占位符
        String url = "https://open.weixin.qq.com/connect/qrconnect?appid=%s&redirect_uri=%s&respose_type=code&" +
                "scope=snsapi_login&state=%s#webchat_redirect";

        //进行url的编码
        String redirectUrl = null;
        try {
            redirectUrl = URLEncoder.encode(WxConstant.WX_REDIRECT_URL, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //填充占位符
        url = String.format(url, WxConstant.WX_APP_ID, redirectUrl, "JNEdu");

        //重定向到对应的微信请求地址
        return "redirect:" + url;
    }

    @GetMapping("/callback")
    public String callback(String code, String state) {
        //1.当扫码成功后返回对应的wxCode以及设置的state，可以用来获取对应的用户的信息
        //2.请求微信开发的固定的API，获取 access_token 和 openId
        //access_token:访问微信的凭证
        //openId:用来区分不同的微信账号的
        try {
            String url = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";
            //携带个人的参数，密钥以及APPid
            url = String.format(url, WxConstant.WX_APP_ID, WxConstant.WX_APP_SECRET, code);
            String responseJson = HttpClientUtils.get(url);
            log.info("获取到的用户的access_token值为：" + responseJson);
            //返回的 responseJson 是一个json字符串，需要转为对应的K-V键值对结构
            HashMap tokenMap = new Gson().fromJson(responseJson, HashMap.class);
            //获取用户的openid以及accessToken
            String accessToken = (String) tokenMap.get("access_token");
            String openid = (String) tokenMap.get("openid");
            //判断数据库中是否存在该用户
            UcenterMember member = ucService.getUserInfoByWXOpenid(openid);
            //如果不存在该用户，则添加用户
            if (null == member){
                //3.凭借上面的两个值发送请求来获取对应的微信用户信息
                url = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                url = String.format(url, accessToken, openid);
                //发送请求获取数据
                String userInfo = HttpClientUtils.get(url);
                log.info("获取到的用户信息为：" + userInfo);
                //将获取到的信息添加到数据库中
                HashMap userMap = new Gson().fromJson(userInfo, HashMap.class);
                //获取用户的头像以及昵称
                String nickname = (String)userMap.get("nickname");
                String avatar = (String)userMap.get("headimgurl");
                member = new UcenterMember();
                member.setNickname(nickname).setAvatar(avatar).setOpenid(openid);
                ucService.saveUser(member);
            }
            //由于cookie不能跨域，需要使用jwt生产对应的用户token携带回首页
            String token = JwtUtils.getJwtToken(member.getId(), member.getNickname());

            return "redirect:http://localhost:3000?token=" + token;
        } catch (Exception e) {
            throw new GlobalException(20001, "登录失败");
        }
    }
}
